<?php
/**
 * Created by Chongyi
 * Date: 2015/10/6 0006
 * Time: 下午 4:25
 */

namespace App\B2BProject\Foundation\Response;


use App\B2BProject\Contract\ResponseDataInterface;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class NormalHttpResponse implements ResponseDataInterface
{
    protected $body;

    protected $code;

    protected $view;

    protected $request;

    public function __construct($body, $code = 200, $view = null, Request $request = null)
    {
        $this->body = $body;
        $this->code = $code;
        $this->view = $view;

        if (is_null($this->request)) {
            $this->request = \Request::instance();
        }
    }

    public function convert()
    {
        if ($this->body instanceof Response) {
            return $this->body;
        }

        if ($this->body instanceof View) {
            return response($this->body, $this->code);
        }

        if (is_array($this->body)) {
            if ($this->request->ajax()) {
                return response()->json(CommonJSONDataParser::parse($this->body), $this->code);
            }

            return response(view($this->view, $this->body), $this->code);
        }

        if (is_string($this->body) && $this->request->ajax()) {
            return response()->json(CommonJSONDataParser::parse($this->body), $this->code);
        }

        return response($this->body, $this->code);
    }
}